package com.znz.analysis.constant.properties;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.alibaba.fastjson.JSONObject;
import com.znz.analysis.constant.JwtConstant;
import com.znz.analysis.util.HttpRequest;
import com.znz.analysis.util.JwtUtil;

/**
 * @author TP
 * @version 创建时间：2017年6月28日 下午3:53:43
 * 
 */
@Configuration
@PropertySource("classpath:external-interface.properties")
public class ExternalInterfaceProperties {

	private static final Logger logger = Logger.getLogger(ExternalInterfaceProperties.class.getName());

	@Resource
	private HttpRequest httpRequest;
	@Resource
	private JwtUtil jwtUtil;
	private String listAllDomain;
	private String ipQuery;

	private String getListAllDomain() {
		return listAllDomain;
	}

	@Value("${api.apollo.listAllDomain}")
	public void setListAllDomain(String listAllDomain) {
		this.listAllDomain = listAllDomain;
	}

	public String getIpQuery() {
		return ipQuery;
	}

	@Value("${api.ip.query}")
	public void setIpQuery(String ipQuery) {
		this.ipQuery = ipQuery;
	}

	/**
	 * 调用API获取apollo相关所有domain
	 * 
	 * @param url
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<String> getDomainsFromApollo() {
		List<String> domains = new ArrayList<String>();
		String url = this.getListAllDomain();
		// 请求头生成token
		Map<String, String> headers = new HashMap<String, String>();
		String subject = jwtUtil.generalSubject(JwtConstant.LOGANALYSIS_SECRETKEY, JwtConstant.LOGANALYSIS_USERNAME,
				JwtConstant.LOGANALYSIS_USERPWD);
		String token = jwtUtil.createJWT(JwtConstant.JWT_ID, subject, JwtConstant.JWT_TTL);
		headers.put("token", token);
		// 发送get请求获取数据
		String response = httpRequest.sendGet(url, null, headers);
		if (StringUtils.isNotBlank(response)) {
			JSONObject jsonObject = JSONObject.parseObject(response);
			if (jsonObject.containsKey("data") && jsonObject.getIntValue("code") == 1000) {
				domains = jsonObject.getJSONArray("data").toJavaObject(List.class);
			} else {
				logger.error("请求域名失败: " + jsonObject);
			}
		}
		return domains;
	}

}
